<template>
  <el-dialog :model-value="dialogVisible" title="选择用户" width="60%" align-center @closed="handleCancel">
    <x-table
      ref="refTable"
      name="用户"
      :height="tableHeight"
      :columns="columns"
      :init-sort="{ userName: 'ascending' }"
      :data="tableData.resp.list"
      :total="tableData.resp.total"
      :loading="tableData.loading"
      :init-query="props.initQuery"
      @query="handleQuery"
    >
      <template #column-userStatus="scope">
        <el-tag v-if="scope.data === 0" type="info">禁用</el-tag>
        <template v-else>启用</template>
      </template>
    </x-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" :disabled="selectCount === 0" @click="handleOk">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick } from 'vue'
import { ElDialog, ElTag } from 'element-plus'
import { util } from '@/utils'
import { useUser } from './hook'

const props = withDefaults(
  defineProps<{
    visible: boolean
    initQuery?: boolean
    api?: (page: AxiosType.Pagination) => Promise<AxiosType.Response>
  }>(),
  {
    visible: false,
    initQuery: true
  }
)
const emits = defineEmits(['ok', 'update:visible'])

const tableHeight = computed(() => util.getAppHeight() * 0.55)

const { refTable, tableData, handleQuery, columns } = useUser(props.api)

const dialogVisible = computed(() => props.visible)
const selectCount = computed(() => (refTable.value ? refTable.value.selection.length : 0))

const handleOk = () => {
  emits('ok', { users: refTable.value.selection })
  emits('update:visible', false)
}
const handleCancel = () => {
  refTable.value.table.clearSelection()
  emits('update:visible', false)
}
const refresh = () => {
  nextTick(() => {
    refTable.value.refresh()
  })
}

defineExpose({ refresh })
</script>

<style lang="scss" scoped></style>
